<template>
  <div class="context">
    <div style="padding: 30px">
      <div style="font-size: 30px"> {{ draft.title}}</div>
      <div style="margin-top: 2%">
        <span> 作者：{{ draft.name }} &nbsp;&nbsp;&nbsp;</span>
        <span> 创作时间： {{ draft.create_time }} &nbsp;&nbsp;&nbsp;</span>
        <span>点击数：{{ draft.watch }} &nbsp;&nbsp;&nbsp;</span>
        <span @click="stars" style="cursor: pointer">是否点赞：{{ starsText }}</span>
      </div>
<!--      <mavon-editor v-model="draft.content"></mavon-editor>-->
      <div id="html" v-html="draft.html" style="margin-top: 2%"></div>
    </div>

  </div>
</template>

<script setup>
import {onMounted,ref} from "vue";
import { useRoute } from 'vue-router'
import axios from "axios";
import "mavon-editor/dist/markdown/github-markdown.min.css";
import hljs from "mavon-editor/dist/highlightjs/highlight.min.js";
import "mavon-editor/dist/highlightjs/styles/github-dark-dimmed.min.css";
import {ElMessage} from "element-plus";
import { nextTick } from 'vue'
const router = useRoute();
const uuid = router.params.uuid


onMounted(()=>{
  // console.log(uuid)
  getDraftsByUUID()
})

const draft = ref({

})

const starsText = ref("");

const getDraftsByUUID = async () =>{
  await axios.get("writes/"+uuid).then(res=>{
    console.log(res)
    draft.value = res.data
    const split = draft.value.create_time.split("T");
    // console.log("时间",split)
    const split1 = split[0].split("-")
    const split2 = split[1].split(":");
    draft.value.create_time = split1[0] + "年" + split1[1] + "月" + split1[2] + "日"
  })

  axios.get("stars/"+uuid).then(res =>{
    starsText.value = res.message
  })

  getCodes();
}

const stars = () =>{
  // console.log("点赞")
  axios.get("/stars/like/"+uuid).then(res =>{
    ElMessage({
      message: res.message,
      type: 'success',
      duration: 2000
    })
    getDraftsByUUID()
  })
}

let codes = "";

// 代码高亮
const getCodes = ()=> {
  codes = document.querySelectorAll("pre code");

  // 设置照片为250 * 250
  const images = document.querySelectorAll("p img")
  images.forEach((image) => {
    image.style.width = "250px";
    image.style.height = "250px";
  });

  if (codes.length > 0) {
    for (let i = 0; i < codes.length; i++) {
      if (codes[i].offsetHeight != 0) {
        return init();
      } else {
        let timer = setInterval(() => {
          for (let j = 0; j < codes.length; j++) {
            if (codes[j].offsetHeight != 0) {
              clearInterval(timer);
              return init();
            }
          }
        }, 500);
        return;
      }
    }
    return;
  }
}
const init = () =>{
  let timer = nextTick(() => {
    clearInterval(timer);
    codes.forEach((item) => {
      // 取出 code 的父元素 pre（后面方便使用）
      let pre = item.parentElement;
      // 添加拖动属性
      // dragAround(item);



      // 新建元素 代码块序号
      let lineNumBox = document.createElement("div");
      lineNumBox.setAttribute(
          "style",
          "height: " + item.offsetHeight + "px"
      );
      lineNumBox.className = "line-num-box";


      // 插入序号 计算方式：获取code元素的高并除以行高，得到行数，根据行数插入序号
      // let num = ""; // 设行高二十
      // for (let i = 1; i < Math.ceil(item.offsetHeight / 20) + 1; i++) {
      //   num += i + "\n"; // 序号加上换行符
      // }
      // lineNumBox.innerText = num; // 插入序号
      // pre.insertBefore(lineNumBox, item);



      let codeBox = document.createElement("div");
      codeBox.className = "code-box";
      codeBox.appendChild(item);
      pre.appendChild(codeBox);



      // let icon =
      //     `<div class="mac-icon">` +
      //     `<span class="mac-icon-red"></span>` +
      //     `<span class="mac-icon-yellow"></span>` +
      //     `<span class="mac-icon-green"></span>` +
          `<!--<button class="copy-button">复制</button>-->`  +
          // `</div>`;
      //

      // pre.insertAdjacentHTML("afterbegin", icon);
      //获取复制元素
      // let copyButton =
      //     pre.firstElementChild.getElementsByClassName("copy-button")[0];
      // copyButton.onclick = function () {
      //   const copyPromise = navigator.clipboard.writeText(
      //       pre.lastElementChild.innerText
      //   );
      //   copyPromise
      //       .then(() => {
      //         ElMessage({
      //           message: "copy成功",
      //           type: "success",
      //           duration: 1200,
      //         });
      //       })
      //       .catch(() => {
      //         ElMessage({
      //           message: "copy失败",
      //           type: "success",
      //           duration: 1200,
      //         });
      //       });
      // };


      hljs.highlightBlock(codeBox.firstElementChild);
    });
  });
}
// 给某个元素添加左右拖动属性
const dragAround = (anyElement)=> {
  let mouseDown = false; // 鼠标是否按下
  let x = 0; // 鼠标点击的下标
  let left = 0; // 当前滚动条位置
  anyElement.onmousedown = function (e) {
    mouseDown = true; // 鼠标按下
    x = e.clientX; // 获取鼠标点击位置 （x坐标）
    left = this.scrollLeft; // 滚动条当前位置
  };
  anyElement.onmousemove = function (e) {
    // 鼠标按下
    if (mouseDown) {
      let curX = e.clientX; // 鼠标移动到当前的位置
      let diffX = curX - x; // 鼠标移动距离（当前位置 减去之前的位置）
      this.scrollLeft = left - diffX;
    }
  };
  anyElement.onmouseup = function () {
    mouseDown = false;
  };
  anyElement.onmouseleave = function () {
    mouseDown = false;
  };
}

const destroyed =()=> {
  clearInterval(this.timer);
}
</script>

<style scoped>
.context{
  margin: 0 auto;
  margin-top: 2%;
  width: 75%;
  /* min-height: 85vh;*/
  background-color: white;
}
</style>

<style scoped>
pre {
  opacity: 1 !important;
  border: 1px solid #272822 !important;
  //border: 1px solid rgb(242,243,245) !important;
  background-color: #272822 !important;
  //background-color: rgb(242,243,245) !important;
  border-radius: 10px !important;
}

.line-num-box {
  display: inline-block !important;
  color: #ccc !important;
  border-right: 2px solid #fff !important;
  line-height: 20px !important;
  font-size: 16px !important;
  text-align: right !important;
  padding-left: 10px !important;
  padding-right: 10px !important;
}

.code-box {
  display: inline-block !important;
  vertical-align: top !important;
  width: calc(100% - 50px) !important;
  border-left-style: none !important;
}

code {
  line-height: 20px !important;
  font-size: 16px !important;
  vertical-align: top;
  padding-top: 0 !important;
  padding-bottom: 0 !important;
  padding-left: 10px !important;
}

code::-webkit-scrollbar {
  height: 10px !important;
  border-radius: 5px !important;
  background-color: #1e1e1e !important;
  /*background-color: rgb(248,248,248);*/
}

code::-webkit-scrollbar-thumb {
  /*滚动条里面小方块*/
  border-radius: 5px !important;
  background-color: #666 !important;
}

code::-webkit-scrollbar-button {
  /*滚动条的轨道的两端按钮，允许通过点击微调小方块的位置*/
  border-radius: 5px !important;
  background-color: #1e1e1e !important;
}

.mac-icon {
  height: 30px !important;
  border-bottom: 1px solid silver !important;
  margin-bottom: 5px !important;
  color: deeppink !important;
}

.mac-icon > span {
  display: inline-block !important;
  letter-spacing: 5px !important;
  word-spacing: 5px !important;
  width: 16px !important;
  height: 16px !important;
  border-radius: 8px !important;
}

.mac-icon-red {
  background-color: red !important;

}

.mac-icon-yellow {
  margin-left: 10px;
  background-color: yellow !important;
}

.mac-icon-green {
  margin-left: 10px;
  background-color: green !important;
}

.mac-icon-lang {
  width: 50px !important;
  padding-left: 10px !important;
  font-size: 16px !important;
  vertical-align: top !important;
}

.copy-button {
  padding: 2px 8px !important;
  color: #ffffff !important;
  background-color: #9999aa !important;
  margin-bottom: 5px !important;
  border-radius: 5px !important;
  outline: none !important;
  border: none !important;
}

.copy-button {
  float: right !important;
}

.copy-button:hover {
  cursor: pointer !important;
  background-color: black !important;
}

.markdown-body .lang- {
  display: block;
  overflow: auto;
  font-size: 16px !important;
  //background: #272822 !important;
  background-color: rgb(242,243,245) !important;
  color: #fff;
}

.markdown-body .hljs {
  display: block;
  overflow: auto;
  font-size: 16px !important;
  background: #272822 !important;
  color: #fff;
}

.hljs,
.hljs-tag,
.hljs-subst {
  color: #f8f8f2 !important;
}

.hljs-strong,
.hljs-emphasis {
  color: #a8a8a2 !important;
}

.hljs-bullet,
.hljs-quote,
.hljs-number,
.hljs-regexp,
.hljs-literal,
.hljs-link {
  color: #ae81ff !important;
}

.hljs-code,
.hljs-title,
.hljs-section,
.hljs-selector-class {
  color: #a6e22e !important;
}

.hljs-strong {
  font-weight: bold;
}

.hljs-emphasis {
  font-style: italic;
}

.hljs-keyword,
.hljs-selector-tag,
.hljs-name,
.hljs-attr {
  color: #f92672 !important;
}

.hljs-symbol,
.hljs-attribute {
  color: #66d9ef !important;
}

.hljs-params,
.hljs-class .hljs-title {
  color: #f8f8f2 !important;
}

.hljs-string,
.hljs-type,
.hljs-built_in,
.hljs-builtin-name,
.hljs-selector-id,
.hljs-selector-attr,
.hljs-selector-pseudo,
.hljs-addition,
.hljs-variable,
.hljs-template-variable {
  color: #e6db74 !important;
}

.hljs-comment,
.hljs-deletion,
.hljs-meta {
  color: #75715e !important;
}
</style>